<template>
  <div class="body" v-loading="loading">
    <div>
      <el-button type="primary" size="small" icon="el-icon-check" @click="doSave" :disabled="header.status === 'audit'">&nbsp;保&nbsp;存&nbsp;</el-button>
      <el-button type="warning" size="small" icon="el-icon-s-promotion" @click="doUnAudit" v-if="header.status === 'audit'">&nbsp;反&nbsp;审&nbsp;</el-button>
      <el-button type="primary" size="small" icon="el-icon-s-promotion" @click="doAudit" v-else :disabled="!header.billNo">&nbsp;审&nbsp;核&nbsp;</el-button>
      <el-button type="success" size="small" icon="el-icon-refresh" @click="getBill(header.billNo, true)" v-if="header.billNo && header.status === 'save'">&nbsp;恢&nbsp;复&nbsp;</el-button>
      <el-button type="danger" size="small" icon="el-icon-delete" @click="doDelete" v-if="header.billNo && header.status === 'save'">&nbsp;删&nbsp;除&nbsp;</el-button>
<!--      <el-button type="success" size="small" icon="el-icon-download" @click="doDownload" v-if="header.status === 'audit'">下载箱号详细</el-button>-->
      <el-button type="primary" size="small" icon="el-icon-finished" @click="doTask" v-if="header.status === 'audit'">下发</el-button>
      <el-button type="info" size="small" icon="el-icon-back" @click="gotoList">&nbsp;返&nbsp;回&nbsp;</el-button>
    </div>
    <el-form ref="form" :model="header" size="small" label-width="80px" :inline="true" class="header">
      <div class="audit_icon iconfont icon-yishenhe" v-if="header.status === 'audit'"></div>
      <div class="header_row">
        <el-form-item style="width:300px;" label="方案编码">{{ header.billNo || '-' }}</el-form-item>
        <el-form-item style="width:300px;" prop="billName" label="方案名称" :rules="[{ required: true, trigger:['blur', 'change'], message: '请输入此项内容' } ]">
          <el-input type="text" size="mini" v-model="header.billName" :disabled="header.status === 'audit'"></el-input>
        </el-form-item>
      </div>
      <div class="header_row">
        <el-form-item style="width:300px;" prop="stockFrom" label="仓库">
          <el-select v-model="header.stockFrom" size="small" clearable class="material" placeholder="请选择仓库" style="margin-right: 10px">
            <el-option v-for="item in this.stockList" :key="item.key" :label="item.key + '：' + item.name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item style="width:300px;" prop="stockTo" label="仓库">
          <el-select v-model="header.stockTo" size="small" clearable class="material" placeholder="请选择仓库" style="margin-right: 10px">
            <el-option v-for="item in this.stockList" :key="item.key" :label="item.key + '：' + item.name" :value="item.key" />
          </el-select>
        </el-form-item>
      </div>
      <div class="header_row">
        <el-form-item style="width:300px;" prop="materialFrom" label="物料">
          <el-select filterable remote :remote-method="e => getMaterialList(e)" v-model="header.materialFrom" size="small" clearable class="material" placeholder="请输入物料编码或者名称" style="margin-right: 10px">
            <el-option v-for="item in this.materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </el-form-item>
        <el-form-item style="width:300px;" prop="materialTo" label="物料">
          <el-select filterable remote :remote-method="e => getMaterialList(e)" v-model="header.materialTo" size="small" clearable class="material" placeholder="请输入物料编码或者名称" style="margin-right: 10px">
            <el-option v-for="item in this.materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </el-form-item>
      </div>
      <div class="header_row">
        <el-form-item style="width:300px; margin-left: 40px" prop="addMaterial" label="">
          <el-checkbox v-model="header.addMaterial" size="mini" :disabled="header.status === 'audit'" label="物料盘点允许增加物料"></el-checkbox>
        </el-form-item>
        <el-switch v-model="header.stockTakeMethod" size="mini" :disabled="header.status === 'audit'" active-text="盲盘" inactive-text="明盘"></el-switch>
        <div style="padding-left: 120px">
          <span style="font-size: 14px">复盘</span>
          <el-switch style="padding-left: 5px" size="mini" :disabled="header.status === 'audit'" v-model="header.review" active-color="#13ce66" inactive-color="#DCDFE6"></el-switch>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { getBoxNo } from '../../utils'

export default {
  data() {
    return {
      loading: false,
      materialLoading: false,
      materialList: [],
      supplierLoading: false,
      supplierList: [],
      header: {},
      boxList: [],
      stockList: [],
      selection: []
    }
  },
  async mounted() {
    await this.getStock()
    let billNo = this.$route.query.billNo
    if (billNo) {
      return this.getBill(billNo)
    } else {
      this.header.batchNo = dayjs().format('YYYYMMDDHHmmss')
    }
  },
  methods: {
    async getStock() {
      this.loading = true;
      try {
        let res = await this.$api.getChildDictionaryListByKeys({
          keys: ['stock']
        });
        if (!res.res) return;
        this.stockList = res.stock;
      } finally {
        this.loading = false;
      }
    },
    formatDate(date) {
      if (!date) return ''
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    },
    gotoList() {
      return this.$router.push('/stockTake/stockTakeList')
    },
    async getBill(billNo, reset) {
      if (reset) {
        try {
          await this.$confirm('恢复后未保存数据将被清除，确定恢复吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } catch(e) {
          return
        }
      }
      this.loading = true
      try {
        let res = await this.callApi('get_stock_take_detail', { billNo })
        if (res.res) {
          this.header = res.header || {}
        }
      } finally {
        this.loading = false
      }
    },
    async doDownload() {
      try {
        await this.$confirm(`确定下载吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('download_purcol_bill_barcode', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.$message.success(`已下载!`)
      } finally {
        this.loading = false
      }
    },
    async doTask() {
      try {
        await this.$confirm(`确定下发吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('to_stock_take_task', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.$message.success(`已下发!`)
      } finally {
        this.loading = false
      }
    },
    async doDelete() {
      try {
        await this.$confirm('确定删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.loading = true
      try {
        let res = await this.callApi('delete_stock_take', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        return this.gotoList()
      } finally {
        this.loading = false
      }
    },
    async doAudit() {
      this.loading = true
      try {
        let res = await this.callApi('audit_stock_take', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.header.status = "audit"
        this.$message.success('审核完成!')
      } finally {
        this.loading = false
      }
    },
    async doUnAudit() {
      this.loading = true
      try {
        let res = await this.callApi('unaudit_stock_take', { billNo: this.header.billNo })
        if (!res.res) {
          return
        }
        this.header.status = "save"
        this.$message.success('反审完成!')
      } finally {
        this.loading = false
      }
    },
    doSave() {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }
        this.loading = true
        let param = {
          billNo: this.header.billNo,
          billName: this.header.billName,
          stockFrom: this.header.stockFrom,
          stockTo: this.header.stockTo,
          materialFrom: this.header.materialFrom,
          materialTo: this.header.materialTo,
          addMaterial: this.header.addMaterial,
          stockTakeMethod: this.header.stockTakeMethod,
          review: this.header.review
        }
        try {
          let res = await this.callApi('save_stock_take', param)
          if (!res.res) {
            return
          }
          this.header.billNo = res.billNo
          this.$message.success('保存完成!')
        } finally {
          this.loading = false
        }
      })
    },
    async getMaterialList(val) {
      if (!val) {
        this.materialList = []
        return
      }
      this.materialLoading = true
      try {
        const res = await this.callApi('get_material_by_key', { key: val, pageSize: 20 })
        if (!res.res) return
        this.materialList = res.data
      } finally {
        this.materialLoading = false
      }
    },
    setMaterialValue() {
      if (this.materialList && this.header.materialNo) {
        for(let i = 0; i < this.materialList.length; i++) {
          if (this.materialList[i].fNumber === this.header.materialNo) {
            this.header.materialName = this.materialList[i].fName
            this.header.materialSpec = this.materialList[i].fSpecification
            break
          }
        }
      } else {
        this.header.materialName = ''
        this.header.materialSpec = ''
      }
    },
    async getSupplierList(val) {
      if (!val) {
        this.supplierList = []
        return
      }
      this.supplierLoading = true
      try {
        const res = await this.callApi('get_supplier_by_key', { key: val, pageSize: 20 })
        if (!res.res) return
        this.supplierList = res.data
      } finally {
        this.supplierLoading = false
      }
    },
    setSupplierValue() {
      if (this.supplierList && this.header.supplierNo) {
        for(let i = 0; i < this.supplierList.length; i++) {
          if (this.supplierList[i].fNumber === this.header.supplierNo) {
            this.header.supplierName = this.supplierList[i].fName
            break
          }
        }
      } else {
        this.header.supplierName = ''
      }
    },
    limitProduceDate(d) {
      return dayjs(d).isAfter(dayjs())
    },
    selectChange(data) {
      this.selection = data
    },
    async deleteDetail() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.selection.forEach(sel => {
        for(let i = 0; i < this.boxList.length; i++) {
          if (this.boxList[i].boxNo === sel.boxNo) {
            this.boxList.splice(i, 1)
            break
          }
        }
      })
    },
    async deleteDetail0() {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      for(let i = this.boxList.length - 1; i >= 0; i--) {
        if (this.boxList[i].count === 0) {
          this.boxList.splice(i, 1)
        }
      }
    },
    addDetail() {
      this.boxList.push({
        count: 0,
        boxNo: getBoxNo('CGSH'),
        inStock: false,
        perInBillNo: ''
      })
    },
    addDetailOnRow(e, scope) {
      if (scope.$index === this.boxList.length - 1) {
        if (e.keyCode === 13) {
          this.addDetail()
          // this.$nextTick(() => {
          //   console.log(this.$refs[ 'row_' + (scope.$index + 1) ]?.input)
          //   this.$refs[ 'row_' + (scope.$index + 1) ]?.input?.focus()
          // })
        }
      }
    },
    async deleteRow(idx) {
      try {
        await this.$confirm('确定删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch(e) {
        return
      }
      this.boxList.splice(idx, 1)
    }
  }
}
</script>

<style lang="scss" scoped>
.body {
  padding: 20px 0;
  .header {
    margin-top: 20px;
    position: relative;
    .header_row {
      display: flex;
      >div {
        flex-shrink: 0;
      }
      :deep(.produceDate) {
        .el-input {
          width: 100%!important;
        }
      }
    }
    .audit_icon {
      position: absolute;
      top: -10px;
      left: 60px;
      font-size: 48px;
      color: red;
    }
    .material {
      width: 100%;
    }
    .p3 {
      :deep(.el-form-item__content) {
        display: flex;
        .comment {
          margin-left: 10px;
          word-break: keep-all;
        }
      }
    }
  }
  .detail_header {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    .stat {
      display: flex;
      font-size: 15px;
      >div {
        display: flex;
        align-items: baseline;
        line-height: 32px;
        .label {
          text-align: right;
          margin-right: 5px;
          color: #aaa;
        }
        .value {
          min-width: 50px;
          margin-right: 10px;
          color: #666;
        }
      }
    }
  }
}
</style>
